<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\WebSocket;


use Selibra\Config\Config;
use Selibra\Di\DI;
use Selibra\WebSocket\MessageParser\JSONParser;
use Selibra\WebSocket\MessageParser\XMLParser;
use Selibra\WebSocket\Protocols\MessageInputInterface;
use Selibra\WebSocket\Protocols\MessageParserInterface;

class MessageParser implements MessageParserInterface
{

    /**
     * @var MessageParserInterface
     */
    protected static MessageParserInterface $messageParser;


    /**
     * 数据解析，暂时只使用JSON
     * @param string $message
     * @return MessageInputInterface
     */
    public function parser(string $message): MessageInputInterface
    {
        return self::getParser()->parser($message);
    }


    /**
     * @return MessageParserInterface
     */
    public static function getParser()
    {
        if (!isset(self::$messageParser)) {
            // 获取配置项
            $configParser = Config::get('websocket.message_parser') ?: 'JSON';

            // 获取实例
            self::$messageParser = self::getParserIns($configParser);
        }
        return self::$messageParser;
    }


    /**
     * @param $parserName
     * @return object|MessageParserInterface
     */
    public static function getParserIns($parserName)
    {
        /** @var MessageParserInterface $parser */
        $parser = null;
        switch ($parserName) {
            case 'JSON':
                $parser = DI::getObjectContext(JSONParser::class);
                break;
            case 'XML':
                $parser = DI::getObjectContext(XMLParser::class);
                break;
            default:
                $parser = DI::getObjectContext($parserName);
        }
        return $parser;
    }
}